//
//  CDAFNClient.m
//  myCoding
//
//  Created by Zhan Yu on 16/1/6.
//  Copyright © 2016年 Coding. All rights reserved.
//

#define kNetworkMethodName @[@"Get", @"Post", @"Put", @"Delete"]

#import "CDAFNClient.h"
//#import "Login.h"

@implementation CDAFNClient

static CDAFNClient *_sharedClient = nil;
static dispatch_once_t onceToken;


#pragma mark - 分享 JSON请求委托
+ (CDAFNClient *)sharedJsonClient
{
    dispatch_once(&onceToken, ^{
        _sharedClient = [[CDAFNClient alloc] initWithBaseURL:[NSURL URLWithString:KbaseURLStr]];
    });
    return _sharedClient;
}

#pragma mark - 改变 JSON请求委托
+ (id)changeJsonClient
{
    _sharedClient = [[CDAFNClient alloc] initWithBaseURL:[NSURL URLWithString:KbaseURLStr]];
    return _sharedClient;
}

#pragma mark - 重写 初始化
- (id)initWithBaseURL:(NSURL *)url
{
    self = [super initWithBaseURL:url];
    if (!self)
    {
        return nil;
    }
    self.responseSerializer = [AFJSONResponseSerializer serializer];
    self.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/plain", @"text/javascript", @"text/json", @"text/html",@"image/jpeg", nil];
    
    [self.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [self.requestSerializer setValue:url.absoluteString forHTTPHeaderField:@"Referer"];
    
    self.securityPolicy.allowInvalidCertificates = YES;/*新增固定 SSL 证书到你的应用有助于防止人在这方面的中间人攻击和其他安全漏洞。   应用程序处理敏感的客户数据或财务信息我们强烈建议路线在使用 SSL 钉扎配置和启用 HTTPS 连接的所有通信.默认是No.不建议在生产*/
    
    return self;
}

#pragma mark - 数据请求（不带显示结果）
- (void)requestJsonDataWithPath:(NSString *)aPath
                     withParams:(NSDictionary*)params
                 withMethodType:(NetworkMethod)method
                       andBlock:(void (^)(id data, NSError *error))block
{
    [self requestJsonDataWithPath:aPath withParams:params withMethodType:method autoShowError:YES andBlock:block];
}

#pragma mark - 数据请求（带显示结果）
- (void)requestJsonDataWithPath:(NSString *)aPath
                     withParams:(NSDictionary*)params
                 withMethodType:(NetworkMethod)method
                  autoShowError:(BOOL)autoShowError
                       andBlock:(void (^)(id data, NSError *error))block
{
    if (!aPath || aPath.length <= 0)
    {
        return;
    }
    //log请求数据
    CDLog(@"\n===========request===========\n%@\n%@:\n%@", kNetworkMethodName[method], aPath, params);
    aPath = [aPath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    //    发起请求
    switch (method)
    {
        case Get:
        {
            //所有 Get 请求，增加缓存机制
            NSMutableString *localPath = [aPath mutableCopy];
            if (params)
            {
                [localPath appendString:params.description];
            }
            CDLog(@"\n=======localPath=====\n%@",localPath);
            [self GET:aPath parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
             {
                 CDLog(@"\n===========response===========\n%@:\n%@", aPath, responseObject);
                 id error = [self handleResponse:responseObject autoShowError:autoShowError];
                 if (error)
                 {
                     responseObject = [NSObject loadResponseWithPath:localPath];
                     block(responseObject, error);
                 }
                 else
                 {
                     if ([responseObject isKindOfClass:[NSDictionary class]])
                     {
                         //判断数据是否符合预期，给出提示
                         if ([responseObject[@"data"] isKindOfClass:[NSDictionary class]])
                         {
                             if (responseObject[@"data"][@"too_many_files"])
                             {
                                 if (autoShowError)
                                 {
                                     [NSObject showHudPromptStr:@"文件太多，不能正常显示"];
                                 }
                             }
                         }
                         [NSObject saveResponseData:responseObject toPath:localPath];
                     }
                     block(responseObject, nil);
                 }
                 
             } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)
             {
                 CDLog(@"\n===========response===========\n%@:\n%@", aPath, error);
                 !autoShowError || [NSObject showError:error];
                 id responseObject = [NSObject loadResponseWithPath:localPath];
                 block(responseObject, error);
             }];
        }break;
            
        case Post:
        {
            [self POST:aPath parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
             {
                 CDLog(@"\n===========response===========\n%@:\n%@", aPath, responseObject);
                 id error = [self handleResponse:responseObject autoShowError:autoShowError];
                 if (error)
                 {
                     block(nil, error);
                 }
                 else
                 {
                     block(responseObject, nil);
                 }
                 
             } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)
             {
                 CDLog(@"\n===========response===========\n%@:\n%@", aPath, error);
                 !autoShowError || [NSObject showError:error];
                 block(nil, error);
             }];
        }break;
            
        case Put:
        {
            [self PUT:aPath parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
             {
                 CDLog(@"\n===========response===========\n%@:\n%@", aPath, responseObject);
                 id error = [self handleResponse:responseObject autoShowError:autoShowError];
                 if (error)
                 {
                     block(nil, error);
                 }
                 else
                 {
                     block(responseObject, nil);
                 }
                 
             } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)
             {
                 CDLog(@"\n===========response===========\n%@:\n%@", aPath, error);
                 !autoShowError || [NSObject showError:error];
                 block(nil, error);
             }];
        }break;
            
        case Delete:
        {
            [self DELETE:aPath parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
             {
                 CDLog(@"\n===========response===========\n%@:\n%@", aPath, responseObject);
                 id error = [self handleResponse:responseObject autoShowError:autoShowError];
                 if (error)
                 {
                     block(nil, error);
                 }
                 else
                 {
                     block(responseObject, nil);
                 }
                 
             } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)
             {
                 CDLog(@"\n===========response===========\n%@:\n%@", aPath, error);
                 !autoShowError || [NSObject showError:error];
                 block(nil, error);
             }];
        }
        default: break;
    }
    
}

#pragma mark - 文件请求API

- (void)requestJsonDataWithPath:(NSString *)aPath file:(NSDictionary *)file withParams:(NSDictionary *)params withMethodType:(NetworkMethod)method andBlock:(void (^)(id, NSError *))block
{/*
  UIImage *image = [UIImage imageNamed:@"about"];
  NSDictionary *mydic = [[NSDictionary alloc] initWithObjectsAndKeys:image,@"image", nil];
  UIImage *tempImage = [mydic objectForKey:@"image"];
  */
    //log请求数据
    CDLog(@"\n===========request===========\n%@:\n%@", aPath, params);
    aPath = [aPath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    // Data
    NSData *data;
    NSString *name, *fileName;
    
    if (file)
    {
        UIImage *image = file[@"image"];
        
        // 缩小到最大 800x800
        //        image = [image scaledToMaxSize:CGSizeMake(500, 500)];
        
        // 压缩
        data = UIImageJPEGRepresentation(image, 1.0);
        if ((float)data.length/1024 > 1000)
        {
            data = UIImageJPEGRepresentation(image, 1024*1000.0/(float)data.length);
        }
        
        name = file[@"name"];
        fileName = file[@"fileName"];
    }
    
    switch (method)
    {
        case Post:
        {
            [self POST:aPath parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData)
            {
                if (file)
                {
                    [formData appendPartWithFileData:data name:name fileName:fileName mimeType:@"image/jpeg"];
                }
                
            } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
            {
                CDLog(@"\n===========response===========\n%@:\n%@", aPath, responseObject);
                id error = [self handleResponse:responseObject];
                if (error)
                {
                    block(nil, error);
                }
                else
                {
                    block(responseObject, nil);
                }
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)
            {
                CDLog(@"\n===========response===========\n%@:\n%@", aPath, error);
                [NSObject showError:error];
                block(nil, error);
            }];
            
        }break;
        default:break;
    }
}

#pragma mark -  非法内容报告
- (void)reportIllegalContentWithType:(IllegalContentType)type
                          withParams:(NSDictionary*)params
{
    NSString *aPath;
    switch (type)
    {
        case IllegalContentTypeTweet: aPath = @"/api/inform/tweet"; break;
        case IllegalContentTypeTopic: aPath = @"/api/inform/topic"; break;
        case IllegalContentTypeProject: aPath = @"/api/inform/project"; break;
        case IllegalContentTypeWebsite: aPath = @"/api/inform/website"; break;
        default: aPath = @"/api/inform/tweet"; break;
    }
    CDLog(@"\n===========request===========\n%@:\n%@", aPath, params);
    
    [self POST:aPath parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
     {
         CDLog(@"\n===========response===========\n%@:\n%@", aPath, responseObject);
         
     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)
     {
         CDLog(@"\n===========response===========\n%@:\n%@", aPath, error);
     }];
}

#pragma mark - 下载图片请求API
- (void)uploadImage:(UIImage *)image path:(NSString *)path name:(NSString *)name params:(id)pramaDic
       successBlock:(void (^)(NSURLSessionTask *operation, id responseObject))success
       failureBlock:(void (^)(NSURLSessionTask *operation, NSError *error))failure
      progerssBlock:(void (^)(CGFloat progressValue))progress
{
    
    NSData *data = UIImageJPEGRepresentation(image, 1.0);
    if ((float)data.length/1024 > 1000)
    {
        data = UIImageJPEGRepresentation(image, 1024*1000.0/(float)data.length);
    }
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyyMMddHHmmss";
    NSString *str = [formatter stringFromDate:[NSDate date]];
    NSString *fileName = [NSString stringWithFormat:@"%@_%@.jpg",@"jjhw", str];
    CDLog(@"\nuploadImageSize\n%@ : %.0f", fileName, (float)data.length/1024);
    
    [self POST:path parameters:pramaDic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData)
     {
         [formData appendPartWithFileData:data name:name fileName:fileName mimeType:@"image/jpeg"];
         
     } progress:^(NSProgress * _Nonnull uploadProgress)
     {
         if (uploadProgress)
         {
             progress(uploadProgress.fractionCompleted);
         }
         
     } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
     {
         CDLog(@"Success: %@ ***** %@", task.response, responseObject);
         id error = [self handleResponse:responseObject];
         if (error && failure)
         {
             failure(task, error);
         }
         else
         {
             success(task, responseObject);
         }
         
     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)
     {
         CDLog(@"Error: %@ ***** %@", task.response, error);
         if (failure)
         {
             failure(task, error);
         }
     }];
}

#pragma mark - 下载声音请求API
- (void)uploadVoice:(NSString *)file
           withPath:(NSString *)path
         withParams:(NSDictionary*)params
           andBlock:(void (^)(id data, NSError *error))block
{
    if (![[NSFileManager defaultManager] fileExistsAtPath:file])
    {
        return;
    }
    
    NSData *data = [NSData dataWithContentsOfFile:file];
    NSString *fileName = [file lastPathComponent];
    
    CDLog(@"\nuploadVoiceSize\n%@ : %.0f", fileName, (float)data.length/1024);
    
    [self POST:path parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData)
     {
         [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"audio/amr"];
         
     } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
     {
         CDLog(@"\n===========response===========\n%@:\n%@", path, responseObject);
         id error = [self handleResponse:responseObject autoShowError:YES];
         if (error)
         {
             block(nil, error);
         }
         else
         {
             block(responseObject, nil);
         }
         
     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)
     {
         CDLog(@"\n===========response===========\n%@:\n%@", path, error);
         [NSObject showError:error];
         block(nil, error);
         
     }];
}


@end

